package com.jagochan.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.jagochan.gateway.config.AuthProperties;
import com.jagochan.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@RequiredArgsConstructor
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request
        ServerHttpRequest request = exchange.getRequest();
        // 判断是否是白名单请求
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }
        // 获取请求头
        String authToken = request.getHeaders().getFirst("authorization");
        Long userId = null;
        try {
            userId = jwtTool.parseToken(authToken);
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 把userId存储到ServerWebExchange中
        String userInfo = userId + "";
        exchange = exchange.mutate().request(builder -> {
            builder.header("user-info", userInfo);
        }).build();

        return chain.filter(exchange);
    }

    private boolean isExclude(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
